// flexible.js
;(function(win, lib) {
    var doc = win.document;
    var docEl = doc.documentElement;
    var metaEl = doc.querySelector('meta[name="viewport"]');
    var flexibleEl = doc.querySelector('meta[name="flexible"]');
    var dpr = 0;
    var scale = 0;
    var tid;
    var flexible = lib.flexible || (lib.flexible = {});

    if (metaEl) {
        var match = metaEl.getAttribute('content').match(/initial\-scale=([\d\.]+)/);
        if (match) {
            scale = parseFloat(match[1]);
            dpr = parseInt(1 / scale);
        }
    } else if (flexibleEl) {
        var content = flexibleEl.getAttribute('content');
        if (content) {
            var initialDpr = content.match(/initial\-dpr=([\d\.]+)/);
            var maximumDpr = content.match(/maximum\-dpr=([\d\.]+)/);
            if (initialDpr) {
                dpr = parseFloat(initialDpr[1]);
                scale = parseFloat((1 / dpr).toFixed(2));
            }
            if (maximumDpr) {
                dpr = parseFloat(maximumDpr[1]);
                scale = parseFloat((1 / dpr).toFixed(2));
            }
        }
    }

    if (!dpr && !scale) {
        var isAndroid = win.navigator.appVersion.match(/android/gi);
        var isIPhone = win.navigator.appVersion.match(/iphone/gi);
        var devicePixelRatio = win.devicePixelRatio;
        if (isIPhone) {
            // iOS下，对于2和3的屏，用2倍的方案，其余的用1倍方案
            if (devicePixelRatio >= 3 && (!dpr || dpr >= 3)) {
                dpr = 3;
            } else if (devicePixelRatio >= 2 && (!dpr || dpr >= 2)){
                dpr = 2;
            } else {
                dpr = 1;
            }
        } else {
            // 其他设备下，仍旧使用1倍的方案
            dpr = 1;
        }
        scale = 1 / dpr;
    }
  
    docEl.setAttribute('data-dpr', dpr);
    if (!metaEl) {
        metaEl = doc.createElement('meta');
        metaEl.setAttribute('name', 'viewport');
        metaEl.setAttribute('content', 'initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no');
        if (docEl.firstElementChild) {
            docEl.firstElementChild.appendChild(metaEl);
        } else {
            var wrap = doc.createElement('div');
            wrap.appendChild(metaEl);
            doc.write(wrap.innerHTML);
        }
    }
  
    function refreshRem(){
        var width = docEl.getBoundingClientRect().width;
        if (width / dpr > 540) {
            width = 540 * dpr;
        }
        var rem = width / 10;
        docEl.style.fontSize = rem + 'px';
        flexible.rem = win.rem = rem;
    }
  
    win.addEventListener('resize', function() {
        clearTimeout(tid);
        tid = setTimeout(refreshRem, 300);
    }, false);
    win.addEventListener('pageshow', function(e) {
        if (e.persisted) {
            clearTimeout(tid);
            tid = setTimeout(refreshRem, 300);
        }
    }, false);
  
    if (doc.readyState === 'complete') {
        doc.body.style.fontSize = 12 * dpr + 'px';
    } else {
        doc.addEventListener('DOMContentLoaded', function(e) {
            doc.body.style.fontSize = 12 * dpr + 'px';
        }, false);
    }
  
  
    refreshRem();
  
    flexible.dpr = win.dpr = dpr;
    flexible.refreshRem = refreshRem;
    flexible.rem2px = function(d) {
        var val = parseFloat(d) * this.rem;
        if (typeof d === 'string' && d.match(/rem$/)) {
            val += 'px';
        }
        return val;
    }
    flexible.px2rem = function(d) {
        var val = parseFloat(d) / this.rem;
        if (typeof d === 'string' && d.match(/px$/)) {
            val += 'rem';
        }
        return val;
    }
  
})(window, window['lib'] || (window['lib'] = {}));

// 轮播图
class Carousel {
    constructor(containerId, interval = 3000) {
      this.container = document.getElementById(containerId);
      this.wrapper = this.container.querySelector('.carousel-wrapper');
      this.slides = this.wrapper.querySelectorAll('.carousel-item');
      this.dotsContainer = this.container.querySelector('.carousel-dots');
      this.pageContainer = this.container.querySelector('.carousel-page');
      this.totalSlides = this.slides.length;
      this.currentIndex = 0;
      this.interval = interval;
      this.autoPlayInterval = null;
  
      // 滑动相关变量
      this.startX = 0;
      this.currentX = 0;
      this.isSwiping = false;
  
      this.init();
    }
  
    // 初始化
    init() {
      this.createDots();
      this.updateDots();
      this.updatePage();
      this.startAutoPlay();
      this.bindEvents();
    }
  
    // 创建点
    createDots() {
      for (let i = 0; i < this.totalSlides; i++) {
        const dot = document.createElement('span');
        dot.classList.add('dot');
        dot.dataset.index = i;
        this.dotsContainer.appendChild(dot);
      }
      this.dots = this.dotsContainer.querySelectorAll('.dot');
    }
  
    // 切换到指定的幻灯片
    goToSlide(index) {
      this.currentIndex = index;
      const offset = -this.currentIndex * 100;
      this.wrapper.style.transform = `translateX(${offset}%)`;
      this.updateDots();
      this.updatePage();
    }
  
    // 更新点的样式
    updateDots() {
      this.dots.forEach((dot, index) => {
        dot.classList.toggle('active', index === this.currentIndex);
      });
    }
  
    // 更新页码
    updatePage() {
      if (this.pageContainer) {
        this.pageContainer.innerHTML = (parseInt(this.currentIndex)+1) +' / '+ this.totalSlides
      }
    }
  
    // 显示下一张幻灯片
    showNextSlide() {
      const nextIndex = (this.currentIndex + 1) % this.totalSlides;
      this.goToSlide(nextIndex);
    }
  
    // 显示上一张幻灯片
    showPreviousSlide() {
      const prevIndex = (this.currentIndex - 1 + this.totalSlides) % this.totalSlides;
      this.goToSlide(prevIndex);
    }
  
    // 自动播放
    startAutoPlay() {
      this.autoPlayInterval = setInterval(() => this.showNextSlide(), this.interval);
    }
  
    // 停止自动播放
    stopAutoPlay() {
      clearInterval(this.autoPlayInterval);
    }
  
    // 绑定事件
    bindEvents() {
      // 点点击事件
      this.dots.forEach(dot => {
        dot.addEventListener('click', () => {
          this.stopAutoPlay();
          const index = parseInt(dot.dataset.index, 10);
          this.goToSlide(index);
          this.startAutoPlay();
        });
      });
  
      // 鼠标悬停
    //   this.container.addEventListener('mouseenter', () => this.stopAutoPlay());
    //   this.container.addEventListener('mouseleave', () => this.startAutoPlay());
  
      // 触摸滑动事件
      this.container.addEventListener('touchstart', this.handleTouchStart.bind(this));
      this.container.addEventListener('touchmove', this.handleTouchMove.bind(this));
      this.container.addEventListener('touchend', this.handleTouchEnd.bind(this));
    }
  
    // 处理 touchstart
    handleTouchStart(event) {
      this.stopAutoPlay();
      this.startX = event.touches[0].clientX;
      this.isSwiping = true;
    }
  
    // 处理 touchmove
    handleTouchMove(event) {
      if (!this.isSwiping) return;
      this.currentX = event.touches[0].clientX;
      const deltaX = this.currentX - this.startX;
  
      // 暂时移动幻灯片以显示滑动效果
      const offset = -this.currentIndex * 100 + (deltaX / this.container.offsetWidth) * 100;
      this.wrapper.style.transform = `translateX(${offset}%)`;
    }
  
    // 处理 touchend
    handleTouchEnd() {
      if (!this.isSwiping) return;
      const deltaX = this.currentX - this.startX;
  
      if (deltaX > 50) {
        // 向右滑动
        this.showPreviousSlide();
      } else if (deltaX < -50) {
        // 向左滑动
        this.showNextSlide();
      } else {
        // 滑动幅度不足，回到当前页
        this.goToSlide(this.currentIndex);
      }
  
      this.isSwiping = false;
      this.startAutoPlay();
    }
}

// 初始化多个轮播图
// new Carousel('carousel1', 3000);
// new Carousel('carousel2', 4000);